<?php

namespace App\Repositories;

use App\Lib\WxMapHandle;
use App\Models\Report;
use App\Models\Staff;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use Illuminate\Support\Facades\Log;

class WxNotifyRepository
{
    public function notify($mall_id=0)
    {
        $app = WxMapHandle::getOfficialAccount($mall_id);

        $app->server->push(function ($message) use ($mall_id){
            // $message['FromUserName'] // 用户的 openid
            // $message['MsgType'] // 消息类型：event, text....
            Log::info($message);

            switch ($message['MsgType']){
                case 'event':
                    if(isset($message['EventKey']) && strpos($message['EventKey'],':') !== false){
                        return $this->wxQrcodeEventSave($message, $mall_id);
                    }
                    break;
            }

            return null;
        });

        return $app->server->serve();
    }

    public function wxQrcodeEventSave($message, $mall_id)
    {
        list($type,$key) = explode(':',$message['EventKey']);

        switch ($type){
            case WxMapRepository::PC_LOGIN_STR://PC登陆
                $staff = Staff::firstOrNew(['wx_openid' => $message['FromUserName']]);
                if(empty($staff->wx_nickname)){
                    $url_data = [
                        'title'       => '完善登陆信息',
                        'description' => '请点击完善登陆信息',
                        'url'         => route('auth.success',$mall_id).'?scene='.WxMapRepository::PC_LOGIN_STR,
                        'image'       => url('/images/kj.png'),
                    ];
                }
                $staff->login_key = $message['Ticket'];
                $staff->save();

                break;
            case WxMapRepository::FOOT_WORK_STR:
                $report = Report::query()->where('wx_ticket', $message['Ticket'])->orderBy('id','desc')->first();
                if(empty($report)){
                    return null;
                }
                $url_data = [
                    'title'       => '查看报告',
                    'description' => '查看检查报告完整信息',
                    'url'         => route('report.detail',$mall_id).'?scene='.WxMapRepository::FOOT_WORK_STR.'&rid='.$report->foot_rid,
                    'image'       => url('/images/kj.png'),
                ];
                if(empty($report->wx_openid)){
                    $report->wx_openid = $message['FromUserName'];
                    $report->save();
                }

                break;
        }

        if(!empty($url_data)){
            $items = [
                new NewsItem($url_data),
            ];
            return new News($items);
        }
        return null;
    }
}
